﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tauren.Business.DLL.Base;
using Tauren.Business.DLL.PositionDLL;
using Tauren.Business.DLL.Resouces;
using Tauren.Business.Entity.Config;
using Tauren.Business.Entity.Const;
using Tauren.Business.Entity.Enum;
using Tauren.Business.Entity.Global;
using Tauren.Business.Entity.Input;
using Tauren.Business.Entity.Model;
using Tauren.Business.Entity.Output;
using Tauren.Business.Infrastructure.Globals;

namespace Tauren.Business.Service.PositionBLL
{
    public class PositionServices : Base.BaseService, IPositionServices
    {
        private IPositionBusiness business;
        /// <summary>
        /// 职位结构
        /// </summary>
        /// <param name="baseDLL"></param>
        /// <param name="connectionBLL"></param>
        /// <param name="resourcesBusiness"></param>
        public PositionServices(IPositionBusiness _business, IConnectionBLLBase connectionBLL, IMenuResourcesBusiness resourcesBusiness) : base(_business, connectionBLL, resourcesBusiness)
        {
            this.business = _business;
            this.ResourcesInfo = this.GetResources(GlobalConst.RESOURCES_FLAG_MODULE_POSITION_KEY);
            this.JudePrmission(GlobalConst.RESOURCES_FLAG_MODULE_POSITION_KEY.ToLower());
        }

        public IResponseMessage Add(Position_Input data)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            if (data is null) return GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA));
            var codes = business.IsPermissionCodeRepeat(0, data.PositionCode);
            if (codes) return GlobalErrorType.GLOBAL_REPEAT_CODE.Failure(this.CommonText(GlobalErrorType.GLOBAL_REPEAT_CODE));
            Position Position;
            ToModel(data, out Position);
            if (data.Parents.Any())
            {
                Position.ParentId = data.Parents.FirstOrDefault().PositionId;
            }
            Position.Enable = true;
            Position.Sequence = business.GetSeq();
            Position.Creator = Global.EmpId;
            Position.Modifier = Global.EmpId;
            Position.Creatdate = DateTime.Now;
            Position.Modifdate = DateTime.Now;
            if (business.Add<Position>(Position) > 0)
                return "".OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_SUCCESSINFO.ToString()));
            else return GlobalErrorType.GLOBAL_SAVE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_FAILURE));
        }

        public IResponseMessage Edit(Position_Input data)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            if (data is null) return GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA));
            var codes = business.IsPermissionCodeRepeat(data.PositionId, data.PositionCode);
            if (codes) return GlobalErrorType.GLOBAL_REPEAT_CODE.Failure(this.CommonText(GlobalErrorType.GLOBAL_REPEAT_CODE));
            Position Position;
            ToModel(data, out Position);
            Position dbModble = business.Get<Position>(Position.PositionId);
            if (dbModble is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            if (data.Parents.Any())
            {
                Position.ParentId = data.Parents.FirstOrDefault().PositionId;
            }
            Position.Creator = dbModble.Creator;
            Position.Modifier = Global.EmpId;
            Position.Creatdate = dbModble.Creatdate;
            Position.Modifdate = DateTime.Now;
            Position.Enable = dbModble.Enable;
            Position.HaveDelete = dbModble.HaveDelete;
            if (business.Update<Position>(Position))
                return "".OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_SUCCESSINFO.ToString()));
            else return GlobalErrorType.GLOBAL_SAVE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_FAILURE));
        }

        public IResponseMessage Delete(int AutoID)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            Position dbModble = business.Get<Position>(AutoID);
            if (dbModble is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            dbModble.Enable = false;
            dbModble.Modifier = Global.EmpId;
            dbModble.HaveDelete = true;
            dbModble.Modifdate = DateTime.Now;
            if (business.Update<Position>(dbModble))
                return "".OnSucceed(this.Resources(GlobalErrorType.GLOBAL_DELETE_SUCCESSINFO));
            else return GlobalErrorType.GLOBAL_DELETE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_DELETE_FAILURE));
        }

        public IResponseMessage Get(int AutoID)
        {
            Position Position = business.Get<Position>(AutoID);
            Position_OutPut _OutPut = new Position_OutPut();
            ToViewModel(Position, out _OutPut);
            if (_OutPut is null) return new Position_OutPut().Succeed();
            Position parentPositions = business.Get<Position>(Position.ParentId);
            if (parentPositions != null)
            {
                Position_OutPut outParent;
                ToViewModel(parentPositions, out outParent);
                _OutPut.Parents.Add(outParent);
            }
            List<PersonInfo> personInfos = business.GetEmployee(Position.PositionId);
            if (personInfos.Any())
            {
                List<PersonInfo_OutPut> info_OutPuts;
                ToViewModel(personInfos, out info_OutPuts);
                info_OutPuts.ForEach(p => { p.DicOnParttime = this.CommonText($"pt{(PartTimeJobType)p.OnParttime}"); });
                _OutPut.PersonInfos = info_OutPuts;
            }
            return _OutPut.Succeed();
        }


        public IResponseMessage Config(string PageType)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            List<OutPutConfig> Fields = new List<OutPutConfig>();

            OutPutConfig config = new OutPutConfig();
            config = new OutPutConfig();
            config.Label = this.Resources("positioncode");
            config.FieldKey = "positionCode";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_POSITION_KEY.ToLower();
            config.ControlType = ControlType.text;
            config.Show = true;
            config.Editor = PageType != "view" && PageType != "edit";
            config.Required = PageType != "view" && PageType != "edit";
            Dictionary<object, object> rule = new Dictionary<object, object>();
            if (PageType != "view")
            {
                #region 添加验证规则

                rule.Add("required", true);
                rule.Add("message", this.Resources("positioncoderequired"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///长度
                rule = new Dictionary<object, object>();
                rule.Add("min", 1);
                rule.Add("max", 20);
                rule.Add("message", this.Resources("positioncodemax"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///正则
                rule = new Dictionary<object, object>();
                rule.Add("pattern", "^([a-zA-Z0-9_]){1,20}$");
                rule.Add("message", this.Resources("positioncoderegx"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
            }
            Fields.Add(config);
            #endregion
            #region 中文名
            config = new OutPutConfig();
            config.Label = this.CommonText("thcnname");
            config.FieldKey = "cnName";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_POSITION_KEY.ToLower();
            config.ControlType = ControlType.textarea;
            config.Show = true;
            config.Editor = PageType != "view";
            config.Required = PageType != "view";
            rule = new Dictionary<object, object>();
            if (PageType != "view")
            {
                rule.Add("required", true);
                rule.Add("message", this.Resources("cnnamerequired"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///长度
                rule = new Dictionary<object, object>();
                rule.Add("min", 1);
                rule.Add("max", 100);
                rule.Add("message", this.Resources("cnnamemax"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
            }
            Fields.Add(config);
            #endregion
            #region 英文名
            config = new OutPutConfig();
            config.Label = this.CommonText("thenname");
            config.FieldKey = "enName";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_POSITION_KEY.ToLower();
            config.ControlType = ControlType.textarea;
            config.Show = true;
            config.Editor = PageType != "view";
            config.Required = PageType != "view";
            rule = new Dictionary<object, object>();
            if (PageType != "view")
            {
                rule.Add("required", true);
                rule.Add("message", this.Resources("ennamerequired"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///长度
                rule = new Dictionary<object, object>();
                rule.Add("min", 1);
                rule.Add("max", 200);
                rule.Add("message", this.Resources("ennamemax"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
            }
            Fields.Add(config);
            #endregion 
            config = new OutPutConfig();
            config.Label = this.Resources("parentname");
            config.FieldKey = "parents";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_POSITION_KEY.ToLower();
            config.ControlType = ControlType.position;
            config.Show = true;
            config.Editor = PageType != "view";
            config.SelectType = SelectType.radio;
            BuliedTableConfig(config.Tables, PageType, new List<FromTableHeader>() { new FromTableHeader { FieldKey = "positionId", Show = false, Primary = true }, new FromTableHeader { FieldKey = "positionCode" }, new FromTableHeader { FieldKey = "cnName" }, new FromTableHeader { FieldKey = "enName" } }, config.Operations);
            config.ExceptDataField = new List<Options>() { new Options() { Label = "positionId", Value = 0 } };
            Fields.Add(config);
            config = new OutPutConfig();
            config.Label = this.Resources("positiontypename");
            config.FieldKey = "positionType";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_POSITION_KEY.ToLower();
            config.ControlType = ControlType.parameter;
            config.Show = true;
            config.Editor = PageType != "view";
            config.Required = PageType != "view";
            config.Options = new List<Options>()
            {
                new Options(){Label=this.Resources("positiontypename0"),Value=0},
                new Options(){Label=this.Resources("positiontypename1"),Value=1},
                new Options(){Label=this.Resources("positiontypename2"),Value=2},
                new Options(){Label=this.Resources("positiontypename3"),Value=3},
                new Options(){Label=this.Resources("positiontypename4"),Value=4},
            };
            Fields.Add(config);
            ///人员
            config = new OutPutConfig();
            config.FieldKey = "personInfos";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_POSITION_KEY.ToLower();
            config.ControlType = ControlType.employee;
            config.Label = this.CommonText("frpersoninfos");
            config.Show = true;
            config.Editor = false;
            BuliedTableConfig(config.Tables, PageType, new List<FromTableHeader>() { new FromTableHeader { FieldKey = "empId", Show = false, Primary = true }, new FromTableHeader { FieldKey = "cnName" }, new FromTableHeader { FieldKey = "enName" }, new FromTableHeader { FieldKey = "dicOnParttime" } }, config.Operations);
            Fields.Add(config);
            return Fields.Succeed();
        }


        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <param name="queryModel"></param>
        /// <returns></returns>
        public IResponseMessage Pages(QueryModel queryModel)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            TableListModel<PagePositionTable> tableListModel = new TableListModel<PagePositionTable>();
            List<TableListHeaderModele> Headers = new List<TableListHeaderModele>();
            Headers.Add(new TableListHeaderModele() { Key = "rowNo", Name = this.CommonText("rowno"), Width = 50, Fixed = true });
            Headers.Add(new TableListHeaderModele() { Key = "positionId", Name = this.Resources("positionid"), Width = 120, Hide = true, Fixed = true });
            Headers.Add(new TableListHeaderModele() { Key = "positionCode", Name = this.Resources("positioncode"), Width = 120, Type = "primary_key", IsTag = true, SorTable = SortType.custom.ToString(), Align = "center", Fixed = true, Filter = true });
            Headers.Add(new TableListHeaderModele() { Key = "cnName", Name = this.CommonText("thcnname"), Type = "primary_name", IsOperation = true, SorTable = SortType.custom.ToString(), Fixed = true, Width = 260, Filter = true });
            Headers.Add(new TableListHeaderModele() { Key = "enName", Name = this.CommonText("thenname"), SorTable = SortType.custom.ToString(), Width = 260, Filter = true });
            Headers.Add(new TableListHeaderModele() { Key = "orgName", Name = this.Resources("orgname"), Width = 160 });
            Headers.Add(new TableListHeaderModele() { Key = "parentName", Name = this.Resources("parentname"), Width = 180 });
            Headers.Add(new TableListHeaderModele() { Key = "positionTypeName", Name = this.Resources("positiontypename"), Width = 160, Align = "center", IsTag = true });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Enable", Name = CommonText("thstate"), IsTag = true, Width = 100, Align = "center", SorTable = SortType.custom.ToString() });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Creator", Name = CommonText("diccreator"), Width = 120, Align = "center" });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Creatdate", Name = CommonText("diccreatdate"), Width = 160, Align = "center" });
            Headers.Add(new TableListHeaderModele() { Key = "action", Name = "操作", Width = 180, Align = "center" });
            List<PageUnitInfoTable> unitListModels = new List<PageUnitInfoTable>();
            long Total = 0;
            List<PagePositionTable> pagePositionTables = business.Pages(queryModel, out Total);
            if (pagePositionTables.Any())
            {
                pagePositionTables.ForEach(o =>
                {
                    o.Dic_Enable = CommonText(o.Enable ? GlobalConst.RESOURCES_CONTENT_ENABLE_KEY : GlobalConst.RESOURCES_CONTENT_DISABLE_KEY);
                    o.Dic_Creator = EmpDictionary.ContainsKey(o.Creator) ? EmpDictionary[o.Creator] : "";
                    o.Dic_Creatdate = o.Creatdate.Value.ToString(GlobalConst.DATE_FORMAT_SECONDS);
                    o.Row_Style = o.Enable ? "" : "danger";
                    o.ParentName = PosDictionary.ContainsKey(o.ParentId) ? PosDictionary[o.ParentId] : "";
                    o.OrgName = o.OrgType.ToLower() == OrgationalType.unit.ToString() ? UnitDictionary.ContainsKey(o.OrgId.Value) ? UnitDictionary[o.OrgId.Value] : "" : (OrgDictionary.ContainsKey(o.OrgId.Value) ? OrgDictionary[o.OrgId.Value] : "");
                    o.PositionTypeName = this.Resources($"positiontypename{o.PositionType}");
                    o.Operations = new List<SystemButton>();
                    if (Global.IsAdmin && (Buttons is null || !Buttons.Any()))
                    {
                        BuliderButtons(o.Operations, o.PositionCode, o.PositionId, ButtomType.edit);
                        BuliderButtons(o.Operations, o.PositionCode, o.PositionId, ButtomType.detaile);
                        BuliderButtons(o.Operations, o.PositionCode, o.PositionId, !o.Enable ? ButtomType.enable : ButtomType.disable);
                        BuliderButtons(o.Operations, o.PositionCode, o.PositionId, ButtomType.delete);
                    }
                    else
                    {
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.edit.ToString()))
                            BuliderButtons(o.Operations, o.PositionCode, o.PositionId, ButtomType.edit);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.detaile.ToString()))
                            BuliderButtons(o.Operations, o.PositionCode, o.PositionId, ButtomType.detaile);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && (o.Value == ButtomType.enable.ToString() || o.Value == ButtomType.disable.ToString())))
                            BuliderButtons(o.Operations, o.PositionCode, o.PositionId, !o.Enable ? ButtomType.enable : ButtomType.disable);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.delete.ToString()))
                            BuliderButtons(o.Operations, o.PositionCode, o.PositionId, ButtomType.delete);
                    }
                });
            }
            tableListModel.Body = pagePositionTables;
            tableListModel.Total = Total;
            tableListModel.Header = Headers;
            if (Global.IsAdmin && (Buttons is null || !Buttons.Any()))
            {
                BuliderButtons(tableListModel.Operations, "", 0, ButtomType.add);
            }
            else
            {
                if (Buttons.Any(o => o.Value == ButtomType.add.ToString()))
                    BuliderButtons(tableListModel.Operations, "", 0, ButtomType.add);
            }
            return tableListModel.Succeed();
        }

        public IResponseMessage Enable(int AutoID)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            Position dbModble = business.Get<Position>(AutoID);
            if (dbModble is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            dbModble.Enable = !dbModble.Enable;
            dbModble.Modifier = Global.EmpId;
            dbModble.Modifdate = DateTime.Now;
            if (business.Update<Position>(dbModble))
                return "".OnSucceed(this.CommonText(dbModble.Enable ? GlobalErrorType.GLOBAL_ENABLE_SUCCESSINFO : GlobalErrorType.GLOBAL_DISABLE_SUCCESSINFO));
            else return dbModble.Enable ? GlobalErrorType.GLOBAL_ENABLE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_ENABLE_FAILURE)) : GlobalErrorType.GLOBAL_DISABLE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_DISABLE_FAILURE));
        }
    }
}
